package com.fzy.common.exception;

import com.fzy.common.entity.Result;
import com.fzy.common.enums.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * 自定义异常处理类
 *
 * @author jinsong6
 * @date 2018/7/24 10:33
 */

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result baseExceptionHandler(BaseException e) {
        logger.error("GlobalExceptionHandler exceptionHandler Exception {}", e);
        return Result.error(e.getCode(), e.getMsg());
    }

    /**
     * 检验不通过返回异常
     *
     * @param e 参数绑定异常
     * @return
     * @author 冯赵杨
     * @create 2018/8/6
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result constraintViolationException(ConstraintViolationException e) {
        String fieldName = "";
        String msg = "";
        String message = e.getMessage();

        if (null != message && !"".equals(message)) {
            String[] items = message.split(":");
            if (items.length > 0) {
                fieldName = items[0].substring(items[0].lastIndexOf(".") + 1);
                msg = items[1];
            }

            return Result.failKV(fieldName, msg);
        } else {
            return Result.error(ErrorCode.PARAM_NOT_LEGAL);
        }

    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        logger.error("GlobalExceptionHandler exceptionHandler Exception {}", e);
        return Result.fail(e.getMessage());
    }
}
